package com.trkj.service;

import java.math.BigDecimal;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.jpa.CcBerthDAO;
import com.trkj.dao.jpa.CcPatientDAO;
import com.trkj.dao.jpa.CcTrimDAO;
import com.trkj.dao.jpa.CcWardDAO;
import com.trkj.pojos.CcBerth;
import com.trkj.pojos.CcPatient;
import com.trkj.pojos.CcTrim;
import com.trkj.pojos.CcWard;

@Service
@Transactional
public class CcTrimService  {

	@Autowired
	private CcTrimDAO ctDAO;
	@Autowired
	private CcPatientDAO patientDAO;
	@Autowired
	private CcBerthDAO ccbDAO;
	@Autowired
	private CcWardDAO ccWardDAO;
	public boolean addCcTrim(String thandleid,String thisbid,String ttremarks,String trimbid,String trimpbid){
		CcTrim ct =new CcTrim();
		ct.setHadate(new Date());
		ct.setTtremarks(ttremarks);
		ct.setThandleid(new BigDecimal(thandleid));
		boolean jg=false;
		if(trimpbid!=null||trimbid!=null){
			if(trimpbid.length()>0){
				CcBerth vv=ccbDAO.findOne(Long.valueOf(trimpbid));
				ct.setOldberthid(new BigDecimal(trimpbid));
				ct.setTrpatientid(vv.getBpId());
				ct.setNewberthid(new BigDecimal(thisbid));
				upshu(trimpbid,thisbid);
			}else{
				CcBerth vv=ccbDAO.findOne(Long.valueOf(thisbid));
				ct.setOldberthid(new BigDecimal(thisbid));
				ct.setTrpatientid(vv.getBpId());
				ct.setNewberthid(new BigDecimal(trimbid));
				upshu(thisbid,trimbid);
			}
			
			upBpatienid(ct.getOldberthid().longValue(),null,"空");
			upBpatienid(ct.getNewberthid().longValue(),ct.getTrpatientid(),"已住人");
			upPaberthid(ct.getTrpatientid().longValue(),ct.getNewberthid());
			
			ctDAO.save(ct);
			jg=true;
		}
		return jg;
	}
	
	public void upPaberthid(long id,BigDecimal paberthid){
		CcPatient cp=patientDAO.findOne(id);
		cp.setPaberthid(paberthid);
		patientDAO.save(cp);
	}
	public void upBpatienid(long id,BigDecimal pid,String state){
		CcBerth cb=ccbDAO.findOne(id);
		cb.setBpId(pid);
		cb.setBerthstate(state);
		ccbDAO.save(cb);
	}
	public void upshu(String oid,String nid){
		CcBerth cb1=ccbDAO.findOne(Long.valueOf(nid));
		CcBerth cb2=ccbDAO.findOne(Long.valueOf(oid));
		if(cb1.getBwardno()!=cb2.getBwardno()){
			CcWard cw1= ccWardDAO.findOne(cb1.getBwardno().longValue());
			int b= Integer.parseInt(cw1.getWpeople())+1;
			cw1.setWpeople(b+"");
			CcWard cw2= ccWardDAO.findOne(cb2.getBwardno().longValue());
			int c= Integer.parseInt(cw2.getWpeople())-1;
			cw2.setWpeople(c+"");
			ccWardDAO.save(cw1);
			ccWardDAO.save(cw2);
		}
		
	}
}
